import 'dart:convert';

/// 安全的类型转换辅助函数

/// 将动态类型转换为int，支持String、int、double等
int _toInt(dynamic value, {int defaultValue = 0}) {
  if (value == null) return defaultValue;
  if (value is int) return value;
  if (value is double) return value.toInt();
  if (value is String) {
    final parsed = int.tryParse(value);
    return parsed ?? defaultValue;
  }
  return defaultValue;
}

/// 将动态类型转换为String
String _toString(dynamic value, {String defaultValue = ''}) {
  if (value == null) return defaultValue;
  if (value is String) return value;
  return value.toString();
}

/// 将动态类型转换为bool
bool _toBool(dynamic value, {bool defaultValue = false}) {
  if (value == null) return defaultValue;
  if (value is bool) return value;
  if (value is int) return value != 0;
  if (value is String) {
    final lower = value.toLowerCase();
    if (lower == 'true' || lower == '1') return true;
    if (lower == 'false' || lower == '0') return false;
  }
  return defaultValue;
}

/// 文章树形结构信息
class NotesTreeVO {
  /// 文章ID
  int notesId;

  /// 文章标题
  String title;

  /// 封面图片
  String coverPicture;

  /// 点赞数
  int notesLikeNum;

  /// 收藏数
  int notesCollectionNum;

  /// 续写层级（从0开始）
  int continuationLevel;

  /// 续写路径
  String continuationPath;

  /// 子文章列表
  List<NotesTreeVO> children;

  /// 是否为根文章
  bool isRoot;

  /// 文章类型（0=图文，1=视频）
  int notesType;

  NotesTreeVO({
    required this.notesId,
    required this.title,
    required this.coverPicture,
    required this.notesLikeNum,
    required this.notesCollectionNum,
    required this.continuationLevel,
    required this.continuationPath,
    required this.children,
    required this.isRoot,
    this.notesType = 0, // 默认为图文类型
  });

  factory NotesTreeVO.fromJson(Map<String, dynamic> json) {
    return NotesTreeVO(
      notesId: _toInt(json['notesId']),
      title: _toString(json['title']),
      coverPicture: _toString(json['coverPicture']),
      notesLikeNum: _toInt(json['notesLikeNum']),
      notesCollectionNum: _toInt(json['notesCollectionNum']),
      continuationLevel: _toInt(json['continuationLevel']),
      continuationPath: _toString(json['continuationPath']),
      children: (json['children'] as List<dynamic>?)
              ?.map((e) => NotesTreeVO.fromJson(e as Map<String, dynamic>))
              .toList() ??
          [],
      isRoot: _toBool(json['isRoot']),
      notesType: _toInt(json['notesType']),
    );
  }

  factory NotesTreeVO.fromJsonString(String jsonString) {
    return NotesTreeVO.fromJson(jsonDecode(jsonString));
  }

  Map<String, dynamic> toJson() {
    return {
      'notesId': notesId,
      'title': title,
      'coverPicture': coverPicture,
      'notesLikeNum': notesLikeNum,
      'notesCollectionNum': notesCollectionNum,
      'continuationLevel': continuationLevel,
      'continuationPath': continuationPath,
      'children': children.map((e) => e.toJson()).toList(),
      'isRoot': isRoot,
      'notesType': notesType,
    };
  }

  String toJsonString() {
    return jsonEncode(toJson());
  }

  /// 获取总节点数（包括自己和所有子孙节点）
  int getTotalNodeCount() {
    int count = 1; // 自己
    for (var child in children) {
      count += child.getTotalNodeCount();
    }
    return count;
  }

  /// 获取最大深度
  int getMaxDepth() {
    if (children.isEmpty) {
      return continuationLevel;
    }
    int maxChildDepth = 0;
    for (var child in children) {
      int childDepth = child.getMaxDepth();
      if (childDepth > maxChildDepth) {
        maxChildDepth = childDepth;
      }
    }
    return maxChildDepth;
  }

  /// 获取所有叶子节点（没有子节点的节点）
  List<NotesTreeVO> getLeafNodes() {
    if (children.isEmpty) {
      return [this];
    }
    List<NotesTreeVO> leaves = [];
    for (var child in children) {
      leaves.addAll(child.getLeafNodes());
    }
    return leaves;
  }

  /// 查找指定ID的节点
  NotesTreeVO? findNodeById(int id) {
    if (notesId == id) {
      return this;
    }
    for (var child in children) {
      var found = child.findNodeById(id);
      if (found != null) {
        return found;
      }
    }
    return null;
  }
}

